package com.tjn.collection_;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
 * @author 陶镓妮
 * @version 1.0
 * Iterator迭代器
 */
public class CollectionIterator {
    public static void main(String[] args) {
        Collection col = new ArrayList();
        col.add(new Book("西游记","吴承恩",100));
        col.add(new Book("红楼梦","曹雪芹",100));
        col.add(new Book("三国演义","罗贯中",100));
        col.add(new Book("水浒传","施耐庵",100));

        //先得到迭代器，再用while循环遍历
        Iterator iterator = col.iterator();//iterator方法可以获取迭代器
        //itit快捷键可以快速创建一个这样的while循环
        while (iterator.hasNext()) {//hasNext方法可以判断集合中下一个地方是否存有元素
            Object obj = iterator.next();//next方法可以获取集合中的下一个元素
            System.out.println(obj);
        }

        //在退出while循环之后，迭代器指向的是最后的元素，如果继续迭代，会报异常
        //iterator.next();

        //如果想要进行第二次迭代，需要重新获取迭代器
        iterator = col.iterator();
        System.out.println("第二次迭代");
        while (iterator.hasNext()) {
            Object obj = iterator.next();
            System.out.println(obj);
        }
    }
}
class Book{
    private String name;
    private String author;
    private double price;

    public Book(String name, String author, double price) {
        this.name = name;
        this.author = author;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                '}';
    }
}